package main

import (
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
)

var OnShutdownHooks = []func(){}

func main() {
	if len(localRemotes) > 0 {
		tunnel := NewSSHTunnel()
		for _, localRemote := range localRemotes {
			local, remote := getLocalRemote(localRemote)
			go tunnel.StartTunnel(local, remote)
		}
	}

	if needOpenReverseHttpServer() {
		startReverseHttpServer()
	}

	waitShutdown()
}

func getLocalRemote(localRemote string) (local, remote string) {
	arr := strings.Split(localRemote, ",")
	return strings.TrimSpace(arr[0]), strings.TrimSpace(arr[1])
}

func registerOnShutdown(f func()) {
	OnShutdownHooks = append(OnShutdownHooks, f)
}

func waitShutdown() {
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	<-sig
	log.Println("shutting down gracefully, press Ctrl+C again to force")
	for _, f := range OnShutdownHooks {
		f()
	}
}
